package com.example.lib_base.mvvm

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.DatePicker
import android.widget.EditText
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType
import java.time.Year
import java.util.Calendar
import kotlin.math.min

abstract class BaseActivity<VDB:ViewDataBinding,VM:BaseViewModel>:AppCompatActivity() {

    //取出泛型参数列表
    private val type by lazy {
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
    }

    val binding by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null,layoutInflater) as VDB
    }

    val viewModel by lazy {
        val clazz = type[1] as Class<VM>
       ViewModelProvider(this)[clazz]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
    }

    abstract fun initView()

    abstract fun initData()

    fun showDateDialog(et:EditText){
        val calendar = Calendar.getInstance()
        DatePickerDialog(this,object :DatePickerDialog.OnDateSetListener{
            override fun onDateSet(p0: DatePicker?, year: Int, moenth: Int, dayofMonth: Int) {
                val mon = if (moenth+1<10)"0"+(moenth+1) else moenth+1
                val day = if (dayofMonth<10)"0"+dayofMonth else dayofMonth
                    et.setText("${year}-${mon}-${day}}")
            }


        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    fun showTimeDialog(et:EditText){
        val calendar = Calendar.getInstance()
        TimePickerDialog(this,object :OnTimeSetListener{
            override fun onTimeSet(p0: TimePicker?, hourOfDay: Int, minute: Int) {
                val h = if(hourOfDay < 10)"0"+hourOfDay else hourOfDay
                val m = if (minute < 10) "0"+ minute else minute
                et.setText("${h}:${m}:00")
            }

        },calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show()
    }
}